/**
 * LED 屏参数设置
 */
import { FC, useEffect } from "react";
import { Form, Input, message, Modal } from "antd";
import { IPoundTypeLedList, postGbSystemSetLedSet } from "../../api";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";

const LedParamsSet: FC<{
  ledParamsSetData?: IPoundTypeLedList;
  handleCallBack: () => void;
  ledParamsSetShow: boolean;
}> = ({ ledParamsSetData, handleCallBack, ledParamsSetShow }) => {
  const [form] = Form.useForm();
  const { validateFields, resetFields, setFieldsValue } = form;
  const handleOk = async () => {
    const values = await validateFields();
    const { code, msg } = (await postGbSystemSetLedSet({
      ...values,
      id: ledParamsSetData?.id,
    })) as {
      code: number;
      msg: string;
    };
    if (code === 20000) {
      message.success("设置成功");
      resetFields();
      handleCallBack();
    } else {
      message.error(msg);
    }
  };

  const handleCancel = async () => {
    handleCallBack();
  };

  useEffect(() => {
    if (ledParamsSetData) {
      setFieldsValue(ledParamsSetData);
    }
  }, [ledParamsSetData, setFieldsValue]);

  return (
    <>
      <Modal
        width={useWindowFontSize(520)}
        title={"设置参数"}
        open={ledParamsSetShow}
        onOk={handleOk}
        onCancel={handleCancel}
        getContainer={false}
      >
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          labelAlign="left"
        >
          <Form.Item
            label="IP地址"
            name="ledIp"
            rules={[{ required: true, message: "请填写IP地址!" }]}
          >
            <Input placeholder="请填写IP地址" />
          </Form.Item>
          <Form.Item
            label="端口号"
            name="ledPort"
            rules={[
              { required: true, message: "请填写端口号!" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (value < 0 || value > 65535) {
                    return Promise.reject("端口号只允许填写0-65535之间的数字!");
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <Input type="number" placeholder="请填写端口号" />
          </Form.Item>
          <Form.Item
            label="分区ID"
            name="zoneId"
            rules={[{ required: true, message: "请输入分区ID!" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default LedParamsSet;
